// 连接处理模块

import { log, checkMcpClientLoaded } from './logger.js';
import { updateUIState, disableCapabilityCheckboxes } from './ui.js';
import { getCurrentServerUrl } from './dom.js';

let currentConnectionType = 'sse';

/**
 * 初始化连接处理模块
 */
export function initConnectionHandlers() {
    const { connectBtn, disconnectBtn, terminateBtn } = window.appDOM;
    
    // 设置连接按钮点击事件
    connectBtn.addEventListener('click', connect);
    
    // 设置断开连接按钮点击事件
    disconnectBtn.addEventListener('click', disconnect);
    
    // 设置终止会话按钮点击事件
    terminateBtn.addEventListener('click', terminateSession);
    
    // 监听连接类型变更
    window.appDOM.connectionTypeTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            if (window.appState.connected) {
                log('请先断开当前连接，再切换连接类型', 'warn');
                return;
            }
            
            currentConnectionType = tab.dataset.type;
            window.appState.currentConnectionType = currentConnectionType;
            
            // 更新UI
            window.appDOM.connectionTypeTabs.forEach(t => {
                if (t.dataset.type === currentConnectionType) {
                    t.classList.add('active');
                } else {
                    t.classList.remove('active');
                }
            });
            
            log(`切换到 ${currentConnectionType.toUpperCase()} 连接类型`, 'info');
            
            // 提示用户URL会根据连接类型自动调整
            if (window.appDOM.serverUrlInput && window.appDOM.serverUrlInput.value) {
                log(`注意：URL将根据${currentConnectionType.toUpperCase()}连接类型自动调整`, 'info');
            }
        });
    });
}

/**
 * 连接服务器
 */
export async function connect() {
    try {
        const serverUrl = getCurrentServerUrl(currentConnectionType, window.appDOM.serverUrlInput);
        if (!serverUrl) {
            log('请输入服务器URL', 'error');
            return;
        }
        
        log(`正在连接 ${currentConnectionType.toUpperCase()} 服务器: ${serverUrl}`, 'info');
        
        // 检查McpClient是否正确加载
        if (!checkMcpClientLoaded()) {
            log('错误: McpClient 未正确加载，请检查client.js是否正确引入', 'error');
            return;
        }
        
        // 重置之前的连接
        if (window.appState.client) {
            await disconnect();
        }
        
        // 创建URL对象
        let urlObj;
        try {
            urlObj = new URL(serverUrl);
        } catch (e) {
            // 如果URL格式不正确，尝试使用当前origin构建
            try {
                urlObj = new URL(serverUrl, window.location.origin);
            } catch (e2) {
                log(`无效的服务器URL: ${e2.message}`, 'error');
                return;
            }
        }
        
        // 获取认证配置
        const authConfig = getAuthConfig();
        
        // 根据连接类型创建相应的transport
        let transportClass;
        let transportOptions = {};
        
        // 处理认证配置
        if (authConfig) {
            log(`使用认证方式: ${authConfig.type}`, 'info');
            
            // 为transport创建请求头
            const headers = {};
            
            if (authConfig.type === 'oauth2') {
                headers['Authorization'] = `Bearer ${authConfig.token}`;
            } else if (authConfig.type === 'basic') {
                // Base64编码用户名和密码
                const credentials = btoa(`${authConfig.username}:${authConfig.password}`);
                headers['Authorization'] = `Basic ${credentials}`;
            }
            
            // 将headers添加到transport选项中
            transportOptions.headers = headers;
        }
        
        switch (currentConnectionType) {
            case 'sse':
                transportClass = window.McpClient.SSEClientTransport || 
                                 (window.McpClient.default && window.McpClient.default.SSEClientTransport);
                if (typeof transportClass !== 'function') {
                    log('错误: SSEClientTransport 不可用', 'error');
                    return;
                }
                log('创建SSE客户端传输对象...', 'debug');
                window.appState.transport = new transportClass(urlObj, {
                    reconnectionOptions: {
                        initialReconnectionDelay: 1000,
                        maxReconnectionDelay: 30000,
                        reconnectionDelayGrowFactor: 1.5,
                        maxRetries: 5
                    },
                    ...transportOptions
                });
                break;
            case 'streamable':
                transportClass = window.McpClient.StreamableHTTPClientTransport || 
                                 (window.McpClient.default && window.McpClient.default.StreamableHTTPClientTransport);
                if (typeof transportClass !== 'function') {
                    log('错误: StreamableHTTPClientTransport 不可用', 'error');
                    return;
                }
                log('创建Streamable HTTP客户端传输对象...', 'debug');
                window.appState.transport = new transportClass(urlObj, transportOptions);
                break;
            case 'websocket':
                transportClass = window.McpClient.WebSocketClientTransport || 
                                 (window.McpClient.default && window.McpClient.default.WebSocketClientTransport);
                if (typeof transportClass !== 'function') {
                    log('错误: WebSocketClientTransport 不可用', 'error');
                    return;
                }
                log('创建WebSocket客户端传输对象...', 'debug');
                window.appState.transport = new transportClass(urlObj, transportOptions);
                break;
            default:
                log(`不支持的连接类型: ${currentConnectionType}`, 'error');
                return;
        }
        
        // 设置transport事件监听器
        setupTransportListeners();
        
        // 获取客户端能力
        const capabilities = getClientCapabilities();
        log(`客户端能力: ${JSON.stringify(capabilities)}`, 'debug');
        
        // 获取Client类
        const Client = window.McpClient.Client || 
                      (window.McpClient.default && window.McpClient.default.Client);
        
        if (typeof Client !== 'function') {
            log('错误: Client 类不可用', 'error');
            return;
        }
        
        // 创建Client实例
        log('创建客户端实例...', 'debug');
        window.appState.client = new Client({
            name: `${currentConnectionType.toUpperCase()} Client Demo`,
            version: "1.0.0"
        }, {
            capabilities: capabilities
        });
        
        // 更新UI状态为连接中
        window.appDOM.connectionStatusSpan.textContent = '初始化中';
        
        // 禁用能力选择框
        disableCapabilityCheckboxes(true);
        
        // 连接服务器
        log('正在初始化连接...', 'info');
        
        // 使用try-catch捕获connect方法可能抛出的异常
        try {
            await window.appState.client.connect(window.appState.transport);
        } catch (connectError) {
            log(`连接初始化失败: ${connectError.message}`, 'error');
            // 如果连接失败，尝试直接与服务器通信
            log('尝试直接使用transport对象与服务器通信...', 'info');
            
            // 这里我们不再依赖client对象，而是直接使用transport对象
            try {
                if (window.appState.transport && typeof window.appState.transport.send === 'function') {
                    // 模拟发送初始化请求 - 添加完整的JSON-RPC 2.0规范字段
                    window.appState.transport.send({
                        jsonrpc: '2.0',
                        id: `init-${Date.now()}`,
                        method: 'initialize',
                        params: {
                            name: `${currentConnectionType.toUpperCase()} Client Demo`,
                            version: '1.0.0',
                            capabilities: capabilities
                        }
                    });
                    log('已发送初始化请求，等待服务器响应...', 'info');
                    // 标记为已连接，即使没有完整的client功能
                    window.appState.connected = true;
                    updateUIState(true);
                } else {
                    throw new Error('transport对象不支持send方法');
                }
            } catch (fallbackError) {
                log(`备用连接方式也失败: ${fallbackError.message}`, 'error');
                updateUIState(false);
                return;
            }
        }
        
        // 如果client初始化成功
        if (window.appState.client && !window.appState.connected) {
            log(`${currentConnectionType.toUpperCase()} 客户端初始化成功!`, 'info');
            window.appDOM.connectionStatusSpan.textContent = '已初始化';
            
            // 显示服务器信息
            try {
                if (typeof window.appState.client.getServerVersion === 'function') {
                    const serverInfo = window.appState.client.getServerVersion();
                    if (serverInfo) {
                        log(`服务器信息: ${JSON.stringify(serverInfo)}`, 'info');
                        window.appDOM.serverInfoSpan.textContent = `${serverInfo.name || '未知'} v${serverInfo.version || '未知'}`;
                    }
                }
            } catch (e) {
                log(`获取服务器信息失败: ${e.message}`, 'warn');
            }
            
            try {
                if (typeof window.appState.client.getServerCapabilities === 'function') {
                    const serverCapabilities = window.appState.client.getServerCapabilities();
                    if (serverCapabilities) {
                        log(`服务器支持的能力: ${JSON.stringify(serverCapabilities)}`, 'info');
                    }
                }
            } catch (e) {
                log(`获取服务器能力失败: ${e.message}`, 'warn');
            }
            
            // 更新会话ID显示
            if (window.appState.transport && window.appState.transport.sessionId) {
                window.appDOM.sessionIdSpan.textContent = window.appState.transport.sessionId;
                log(`已建立${currentConnectionType.toUpperCase()}会话: ${window.appState.transport.sessionId}`, 'info');
            }
            
            // 更新UI状态
            window.appState.connected = true;
            try {
                const serverCapabilities = window.appState.client && typeof window.appState.client.getServerCapabilities === 'function' ? 
                                          window.appState.client.getServerCapabilities() : null;
                updateUIState(true, serverCapabilities);
            } catch (e) {
                updateUIState(true);
            }
        }
        
    } catch (error) {
        log(`连接过程中发生错误: ${error.message}`, 'error');
        if (error.stack) {
            log(`错误堆栈: ${error.stack}`, 'debug');
        }
        updateUIState(false);
    }
}

/**
 * 设置transport事件监听器
 */
export function setupTransportListeners() {
    const { transport } = window.appState;
    if (!transport) return;
    
    // 消息事件
    if (typeof transport.onmessage === 'function' || typeof transport.onmessage === 'undefined') {
        transport.onmessage = (message) => {
            if (message && message.data) {
                try {
                    const parsedData = typeof message.data === 'string' ? JSON.parse(message.data) : message.data;
                    log(`收到消息: ${JSON.stringify(parsedData)}`, 'info');
                    // 如果是服务器发送的sessionId，更新显示
                    if (parsedData.sessionId && !window.appDOM.sessionIdSpan.textContent) {
                        window.appDOM.sessionIdSpan.textContent = parsedData.sessionId;
                        log(`已接收到会话ID: ${parsedData.sessionId}`, 'info');
                    }
                    // 如果是服务器能力信息，更新显示
                    if (parsedData.serverCapabilities && !window.appDOM.serverInfoSpan.textContent) {
                        log(`已接收到服务器能力: ${JSON.stringify(parsedData.serverCapabilities)}`, 'info');
                        updateUIState(true, parsedData.serverCapabilities);
                    }
                } catch (e) {
                    log(`收到消息: ${String(message.data)}`, 'info');
                }
            } else {
                log(`收到消息: ${JSON.stringify(message)}`, 'info');
            }
        };
    } else {
        log('警告: transport对象不支持onmessage事件', 'warn');
    }
    
    // 错误事件
    if (typeof transport.onerror === 'function' || typeof transport.onerror === 'undefined') {
        transport.onerror = (error) => {
            if (!error) {
                log('连接错误: 未知错误', 'error');
            } else {
                log(`连接错误: ${error.message || String(error) || '未知错误'}`, 'error');
            }
            updateUIState(false);
        };
    } else {
        log('警告: transport对象不支持onerror事件', 'warn');
    }
    
    // 关闭事件
    if (typeof transport.onclose === 'function' || typeof transport.onclose === 'undefined') {
        transport.onclose = () => {
            log('连接已关闭', 'info');
            updateUIState(false);
            window.appDOM.sessionIdSpan.textContent = '-';
            window.appDOM.serverInfoSpan.textContent = '-';
        };
    } else {
        log('警告: transport对象不支持onclose事件', 'warn');
    }
}

/**
 * 断开连接
 */
export async function disconnect() {
    try {
        if (!window.appState.transport && !window.appState.client) {
            log('未建立连接', 'info');
            return;
        }
        
        log('正在断开连接...', 'info');
        
        // 尝试使用client的disconnect方法
        if (window.appState.client && typeof window.appState.client.disconnect === 'function') {
            try {
                await window.appState.client.disconnect();
                log('客户端断开连接成功', 'info');
            } catch (e) {
                log(`客户端断开连接出错: ${e.message}`, 'warn');
            }
        }
        
        // 如果client断开连接失败，尝试直接关闭transport
        if (window.appState.transport && typeof window.appState.transport.close === 'function') {
            try {
                await window.appState.transport.close();
                log('传输层连接已关闭', 'info');
            } catch (e) {
                log(`传输层关闭出错: ${e.message}`, 'warn');
            }
        }
        
        // 重置状态
        window.appState.client = null;
        window.appState.transport = null;
        window.appState.connected = false;
        
        // 更新UI
        updateUIState(false);
        window.appDOM.sessionIdSpan.textContent = '-';
        window.appDOM.serverInfoSpan.textContent = '-';
        
    } catch (error) {
        log(`断开连接过程中发生错误: ${error.message}`, 'error');
    }
}

/**
 * 终止会话
 */
export async function terminateSession() {
    try {
        if (!window.appState.transport && !window.appState.client) {
            log('未建立连接', 'info');
            return;
        }
        
        log('正在终止会话...', 'info');
        
        // 尝试使用client的terminate方法
        if (window.appState.client && typeof window.appState.client.terminate === 'function') {
            try {
                await window.appState.client.terminate();
                log('客户端会话已终止', 'info');
            } catch (e) {
                log(`客户端终止会话出错: ${e.message}`, 'warn');
            }
        }
        
        // 如果client终止会话失败，尝试直接关闭transport
        if (window.appState.transport && typeof window.appState.transport.close === 'function') {
            try {
                await window.appState.transport.close();
                log('传输层连接已关闭', 'info');
            } catch (e) {
                log(`传输层关闭出错: ${e.message}`, 'warn');
            }
        }
        
        // 重置状态
        window.appState.client = null;
        window.appState.transport = null;
        window.appState.connected = false;
        
        // 更新UI
        updateUIState(false);
        window.appDOM.sessionIdSpan.textContent = '-';
        window.appDOM.serverInfoSpan.textContent = '-';
        
    } catch (error) {
        log(`终止会话过程中发生错误: ${error.message}`, 'error');
    }
}

/**
 * 获取认证配置信息
 * @returns {Object|null} 认证配置对象，如果未启用认证则返回null
 */
export function getAuthConfig() {
    if (!window.appDOM.authCheckbox || !window.appDOM.authCheckbox.checked) {
        return null;
    }
    
    const authType = window.appDOM.authTypeSelect.value;
    
    if (authType === 'oauth2') {
        const token = window.appDOM.oauth2TokenInput.value.trim();
        if (token) {
            return {
                type: 'oauth2',
                token: token
            };
        }
    } else if (authType === 'basic') {
        const username = window.appDOM.basicUsernameInput.value.trim();
        const password = window.appDOM.basicPasswordInput.value.trim();
        if (username && password) {
            return {
                type: 'basic',
                username: username,
                password: password
            };
        }
    }
    
    return null;
}

/**
 * 获取客户端能力
 * @returns {Object} 客户端能力对象
 */
export function getClientCapabilities() {
    const capabilities = {};
    
    window.appDOM.capabilityCheckboxes.forEach(checkbox => {
        const capabilityName = checkbox.id.replace('capability-', '');
        capabilities[capabilityName] = checkbox.checked;
    });
    
    // 根据认证复选框状态决定是否添加认证方式支持
    if (window.appDOM.authCheckbox && window.appDOM.authCheckbox.checked) {
        capabilities.authentication = ['oauth2', 'basic'];
    }
    
    return capabilities;
}